package com.gxa.ehome.controller;

import com.gxa.ehome.pojo.SysUser;
import com.gxa.ehome.service.SysUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/index")
public class IndexController {
    //响应前端请求,没有页面可以展示
    //请求hello响应的过程中,获取web程序中的对象
    //HTTPServlet/HTTPServletRequest/HTTPServletResponse
    //ServletContext/servletConfig/Session/cookie


    @RequestMapping("/hello")
    @ResponseBody
    public void hello(HttpServletRequest request){

        System.out.println("有前端发起了对/index/hello的请求");
        System.out.println(request);
//获取当前servlet(DispatcherServlet)的上下文对象
        ServletContext servletContext = request.getServletContext();
//通过上下文兑现g,huoqu资源的本地路径
        //  /表示当前运行的java程序所在本地目录
        System.out.println(servletContext.getRealPath("/"));
    }
    //访问jsp页面,springmvc的返回值就是在转发
    //将数据代入jsp:request.setAttribute()
    //modelMap:存放你数据的数据模型
    //ModelAndView:包含数据和页面信息整合对象
    //@ModelAttribute:通过name/value指定数据的名称,可以吧方法中定义好的对象传递

    @RequestMapping("/index")
   // @ModelAttribute(name = "username",value = "admin")
    public String index(ModelMap modelMap){
        modelMap.addAttribute("username","admin");
        //return "/WEB-INF/jsp/index.jsp";
        return "index";
    }
    //利用produces(设定响应方式,来解决直接使用@RequestMapping给前段传递中文字字符串
    // application/json;charset=utf-8)
    //几乎没有应用场景
    @RequestMapping(value = "/string",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String getString(){
        return "你好,来了老弟";
    }
    //当我们要给前端返回对象,实际上是对对象做json格式的转换处理
    //使用fastjson等json工具做序列化处理:{jobNumber:"GL001",name:"张三"}
    //否则会抛出No converter found
    //解决方法:fastjson(不推荐)/Jackson(推荐)
    //只需要导入jackson的jar包
    @RequestMapping("/sysUser")
    @ResponseBody//返回json格式数据
    public SysUser getSysUser(){
        SysUser sysUser = new SysUser();
        sysUser.setuserName("adsafs");
        sysUser.setJobNumber("GL00");
        return sysUser;
    }


    @RequestMapping("/list")
    @ResponseBody
    public List<SysUser> getList(@RequestHeader("token") String token){
        List<SysUser> all = sysUserService.findAll();
         return all;
    }
    @Resource
    SysUserService sysUserService=null;
    @RequestMapping("/selectAll")
    @ResponseBody
    public Map<String, Object> selectAll(){
        List<SysUser> all = sysUserService.findAll();
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("data", all);

        return objectObjectHashMap;
    }


}
